package cqrtplm.service.impl;

import com.ty.basic.entity.org.UserDO;
import com.ty.basic.service.snow.SnowflakeIdComponent;
import com.ty.basic.session.TyAccountContext;
import cqrtplm.constant.RTErrorCodeEnum;
import cqrtplm.dto.RTCertFiledFormDTO;
import cqrtplm.entity.RtCertFiledCustomerDO;
import cqrtplm.entity.RtCertFiledPartManufacturDO;
import cqrtplm.mapper.RtCertFiledPartManufacturMapper;
import cqrtplm.service.RtCertFiledPartManufacturService;
import cqrtplm.util.RTLogHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 零件供应商服务实现
 */
@Service
@Slf4j
public class RtCertFiledPartManufacturServiceImpl implements RtCertFiledPartManufacturService {

    @Resource
    private RtCertFiledPartManufacturMapper rtCertFiledPartManufacturMapper;

    @Resource
    private RTLogDifferenceServiceImpl rtLogDifferenceService;

    @Resource
    private SnowflakeIdComponent snowflakeIdComponent;

    @Resource
    private RTLogHelper rtLogHelper;

    @Override
    public List<RtCertFiledPartManufacturDO> selectRtCertFiledPartManufacturList(RtCertFiledPartManufacturDO rtCertFiledPartManufactur) {
        return rtCertFiledPartManufacturMapper.selectRtCertFiledPartManufacturList(rtCertFiledPartManufactur);
    }

    @Override
    public RtCertFiledPartManufacturDO selectRtCertFiledPartManufacturById(String id) {
        return rtCertFiledPartManufacturMapper.selectRtCertFiledPartManufacturById(id);
    }

    @Override
    public RtCertFiledPartManufacturDO selectRtCertFiledPartManufacturByPartId(String partId) {
        RtCertFiledPartManufacturDO q = new RtCertFiledPartManufacturDO();
        q.setPartId(partId);

        List<RtCertFiledPartManufacturDO> result = rtCertFiledPartManufacturMapper.selectRtCertFiledPartManufacturByDO(q);
        return result.isEmpty() ? null : result.get(0);
    }

    @Override
    public int insertRtCertFiledPartManufactur(RtCertFiledPartManufacturDO rtCertFiledPartManufactur) {
        RtCertFiledPartManufacturDO q = new RtCertFiledPartManufacturDO();
        if(rtCertFiledPartManufactur.getPartId() != null && !rtCertFiledPartManufactur.getPartId().isEmpty())
            q.setPartId(rtCertFiledPartManufactur.getPartId());
        q.setFiledId(rtCertFiledPartManufactur.getFiledId());
        if(rtCertFiledPartManufactur.getPartCode() != null && !rtCertFiledPartManufactur.getPartCode().isEmpty())
            q.setPartCode(rtCertFiledPartManufactur.getPartCode());
        q.setManufacturerId(rtCertFiledPartManufactur.getManufacturerId());

        List<RtCertFiledPartManufacturDO> old = rtCertFiledPartManufacturMapper.selectRtCertFiledPartManufacturByDO(q);
        if(old != null && !old.isEmpty()) {
            throw RTErrorCodeEnum.DATA_EXISTS.getException("该零件供应商已存在，请勿重复添加");
        } else {
            UserDO user = TyAccountContext.getUser();
            if (user == null) {
                throw new RuntimeException("用户未登录");
            }

            String snowId = String.valueOf(snowflakeIdComponent.getInstance().nextId());
            Timestamp timestamp = new Timestamp(new Date().getTime());

            rtCertFiledPartManufactur.setId(snowId);
            rtCertFiledPartManufactur.setCreateTime(timestamp);
            rtCertFiledPartManufactur.setCreateUserId(String.valueOf(user.getOid()));
            rtCertFiledPartManufactur.setCreateUserName(user.getName());

            log.info("零件供应商-新增{},{},{},{}",
                     rtCertFiledPartManufactur.getManufacturer(),
                     snowId,
                     timestamp,
                     user.getName());

            return rtCertFiledPartManufacturMapper.insertRtCertFiledPartManufactur(rtCertFiledPartManufactur);
        }
    }

    @Override
    public int updateRtCertFiledPartManufactur(RtCertFiledPartManufacturDO rtCertFiledPartManufactur) {
        RtCertFiledPartManufacturDO old = rtCertFiledPartManufacturMapper.selectRtCertFiledPartManufacturById(rtCertFiledPartManufactur.getId());
        if(old == null) {
            throw RTErrorCodeEnum.DATA_NOT_EXISTS.getException("该零件供应商不存在，请检查");
        } else {
            UserDO user = TyAccountContext.getUser();
            if (user == null) {
                throw new RuntimeException("用户未登录");
            }

            Timestamp timestamp = new Timestamp(new Date().getTime());
            rtCertFiledPartManufactur.setUpdateTime(timestamp);
            rtCertFiledPartManufactur.setUpdateUserId(String.valueOf(user.getOid()));
            rtCertFiledPartManufactur.setUpdateUserName(user.getName());

            int r = rtCertFiledPartManufacturMapper.updateRtCertFiledPartManufactur(rtCertFiledPartManufactur);
            if(r > 0) {
                // 记录差异日志
                rtLogDifferenceService.newLog(
                        rtCertFiledPartManufactur, old,
                        rtCertFiledPartManufactur.getId(),
                        rtCertFiledPartManufactur.getCreateUserName(),
                        "零件供应商",
                        "修改",
                        ""
                );
            }
            return r;
        }
    }

    @Override
    public void updateEntityList(RTCertFiledFormDTO formDTO, String partID, List<RtCertFiledPartManufacturDO> list) {
        String filedId = formDTO.getRtCertFiledDO().getId();
        // 获取数据库中现有的客户列表
        if(!list.isEmpty()){
            RtCertFiledPartManufacturDO q = new RtCertFiledPartManufacturDO();
            q.setPartId(partID);
            q.setFiledId(filedId);
            List<RtCertFiledPartManufacturDO> existingList = selectRtCertFiledPartManufacturList(q);

            // 获取数据库中所有存在的ID集合
            Set<String> existingIds = existingList.stream()
                    .map(RtCertFiledPartManufacturDO::getId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toSet());
            // 编辑操作进行增量处理

            // 1. 找出需要删除的记录（存在于数据库但不在新列表中）
            List<RtCertFiledPartManufacturDO> toDelete = existingList.stream()
                    .filter(existing -> list.stream().noneMatch(newItem -> Objects.equals(newItem.getId(), existing.getId())))
                    .collect(Collectors.toList());

            // 2. 找出需要更新的记录（ID匹配但内容不同）
            List<RtCertFiledPartManufacturDO> toUpdate = list.stream()
                    .filter(item -> item.getId() != null && existingIds.contains(item.getId().toString()))
                    .collect(Collectors.toList());

            // 3. 找出需要新增的记录（ID为null或不在数据库中）
            List<RtCertFiledPartManufacturDO> toInsert = list.stream()
                    .filter(item -> item.getId() == null || !existingIds.contains(item.getId().toString()))
                    .collect(Collectors.toList());


            // 执行操作
            if (Boolean.FALSE.equals(formDTO.getEditWithoutDelete())) {
                toDelete.forEach(item -> deleteRtCertFiledPartManufacturById(item.getId()));
            }
            toUpdate.forEach(item -> {
                item.setFiledId(filedId);
                item.setPartId(partID);
                updateRtCertFiledPartManufactur(item);
            });
            toInsert.forEach(item -> {
                item.setFiledId(filedId);
                item.setPartId(partID);
                insertRtCertFiledPartManufactur(item);
            });
        }
    }

    @Override
    public int deleteRtCertFiledPartManufacturById(String id) {
        return rtCertFiledPartManufacturMapper.deleteRtCertFiledPartManufacturById(id);
    }

    @Override
    public int deleteRtCertFiledPartManufacturByFiledId(String id) {
        return rtCertFiledPartManufacturMapper.deleteRtCertFiledPartManufacturByFiledId(id);
    }

    @Override
    public int deleteRtCertFiledPartManufacturByIds(List<String> ids) {
        return rtCertFiledPartManufacturMapper.deleteRtCertFiledPartManufacturByIds(ids);
    }

    @Override
    public List<RtCertFiledPartManufacturDO> selectRtCertFiledPartManufacturByFiledId(String id) {
        return rtCertFiledPartManufacturMapper.selectRtCertFiledPartManufacturByFiledId(id);
    }
}
